package com.iamnh.basic.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;

import com.iamnh.basic.model.Pager;
import com.iamnh.basic.model.SystemContext;

/**
 * @author BccLj
 * @param <T>
 */
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T>  implements BaseDao<T> {
	
	@Inject
	private SessionFactory sessionFactory;
	
	
	public SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	
	private Class<T> clz;
	
	public Class<T> getClz(){
		if(null == clz){
			Type type = getClass().getGenericSuperclass();
			Type trueType = ((ParameterizedType) type).getActualTypeArguments()[0];
			clz = (Class<T>) trueType;
		}
		return clz;
	}
	protected Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public T add(T t) {
		getSession().save(t);
		return t;
	}

	@Override
	public void update(T t) {
		getSession().update(t);
	}

	@Override
	public void delete(int id) {
		getSession().delete(this.load(id));
	}

	
	@Override
	public T load(int id) {
		return (T)getSession().load(getClz(), id);
	}

	@Override
	public List<T> list(String hql, Object[] args) {
		return this.list(hql, args, null);
	}

	@Override
	public List<T> list(String hql, Object arg) {
		return this.list(hql, new Object[]{arg});
	}

	@Override
	public List<T> list(String hql) {
		return this.list(hql, null);
	}

	@Override
	public List<T> listByAlias(String hql, Map<String, Object> alias) {
		return this.list(hql, null, alias);
	}

	@Override
	public List<T> list(String hql, Object[] args, Map<String, Object> alias) {
		hql = initSort(hql);
		Query query = getSession().createQuery(hql);
		setAliasParameter(query, alias);
		setParameter(query, args);
		return query.list();
	}
	
	private void setParameter(Query query, Object[] args) {
		if(null != args && args.length>0){
			int index = 0;
			for(Object arg:args){
				query.setParameter(index++,arg);
			}
		}
	}
	private void setAliasParameter(Query query, Map<String, Object> alias) {
		if(null != alias){
			Set<String> keys = alias.keySet();
			for(String key : keys){
				Object val = alias.get(key);
				if(val instanceof Collection){
					query.setParameterList(key, (Collection<Object>)val);
				}else{
					query.setParameter(key, val);
				}
			}
		}
	}
	/**
	 * 初始化排序
	 * @param hql
	 * @return
	 */
	private String initSort(String hql) {
		String order = SystemContext.getOrder();
		String sort = SystemContext.getSort();
		if(null != sort && !"".equals(sort.trim())){
			hql += "  order by  "+sort;
			if(!"desc".equals(order)){
				hql += " asc ";
			}else{
				hql += " desc" ;
			}
		}
		return hql;
	}

	@Override
	public Pager<T> find(String hql, Object[] args) {
		return this.find(hql, args, null);
	}

	@Override
	public Pager<T> find(String hql, Object arg) {
		return this.find(hql, new Object[]{arg});
	}

	@Override
	public Pager<T> find(String hql) {
		return this.find(hql, null);
	}

	@Override
	public Pager<T> findByAlias(String hql, Map<String, Object> alias) {
		return this.find(hql, null, alias);
	}

	@SuppressWarnings("rawtypes")
	private void setPagers(Query query,Pager pagers){
		Integer pageSize = SystemContext.getPageSize();
		Integer pageOffset = SystemContext.getPageOffset();
		if( null == pageOffset ||pageOffset < 0){
			pageOffset = 0;
		}
		if( null == pageSize || pageSize < 0){
			pageSize = 15;
		}
		pagers.setOffset(pageOffset);
		pagers.setSize(pageSize);
		query.setFirstResult(pageOffset).setMaxResults(pageSize);
	}
	
	private String getCountHql(String hql,boolean isHql){
		String e = hql.substring( hql.indexOf("from"));
		String c = " select count(*)  " + e;
		if(isHql){
			c.replaceAll("fetch", "");
		}
		return c;
	}
	@Override
	public Pager<T> find(String hql, Object[] args, Map<String, Object> alias) {
		hql = initSort(hql);
		String cq = this.getCountHql(hql,true);
		Query cquery = getSession().createQuery(cq);
		Query query = getSession().createQuery(hql);
		setAliasParameter(query, alias);
		setParameter(query, args);
		setAliasParameter(cquery, alias);
		setParameter(cquery, args);
		Pager<T> pages = new Pager<T>();
		setPagers(query,pages);
		List<T> datas = query.list();
		long total = (Long)cquery.uniqueResult();
		pages.setTotal(total);
		pages.setDatas(datas);
		return pages;
	}

	@Override
	public Object queryObject(String hql, Object[] args) {
		return this.queryObject(hql, args, null);
	}

	@Override
	public Object queryObject(String hql, Object arg) {
		return this.queryObject(hql, new Object[]{arg});
	}

	@Override
	public Object queryObject(String hql, Object[] args, Map<String, Object> alias) {
	    Query query = getSession().createQuery(hql);
		this.setAliasParameter(query, alias);
		this.setParameter(query, args);
		return query.uniqueResult();
	}
	@Override
	public Object queryObjectByAlias(String hql, Map<String, Object> alias) {
		return this.queryObject(hql, null, alias);
	}
	
	@Override
	public Object queryObject(String hql) {
		return this.queryObject(hql, null);
	}

	@Override
	public void updateByHql(String hql, Object[] args) {
		Query query = getSession().createQuery(hql);
		setParameter(query, args);
		query.executeUpdate();
	}

	@Override
	public void updateByHql(String hql, Object arg) {
		this.updateByHql(hql, new Object[]{arg});

	}

	@Override
	public void updateByHql(String hql) {
		this.updateByHql(hql,null);
	}

	@Override
	public <N extends Object>List<N> listBySql(String sql, Object[] args, Class<?> clz, boolean hasEntity) {
		return this.listBySql(sql, args, null, clz, hasEntity);
	}

	@Override
	public <N extends Object>List<N> listBySql(String sql, Object arg, Class<?> clz, boolean hasEntity) {
		return this.listBySql(sql, new Object[]{arg}, clz, hasEntity);
	}

	@Override
	public <N extends Object>List<N> listBySql(String sql, Class<?> clz, boolean hasEntity) {
		return this.listBySql(sql, null, clz, hasEntity);
	}

	@Override
	public <N extends Object>List<N> listBySql(String sql, Object[] args, Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		sql = initSort(sql);
		SQLQuery sq = getSession().createSQLQuery(sql);
		this.setParameter(sq, args);
		this.setAliasParameter(sq, alias);
		if(hasEntity){
			sq.addEntity(clz);
		}else{
			sq.setResultTransformer(Transformers.aliasToBean(clz));
		}
		return sq.list();
	}

	@Override
	public <N extends Object>List<N> listByAliasSql(String sql, Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		return this.listBySql(sql, null, alias, clz, hasEntity);
	}

	@Override
	public <N extends Object>Pager<N> findBySql(String sql, Object[] args, Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, args, null, clz, hasEntity);
	}

	@Override
	public <N extends Object>Pager<N> findBySql(String sql, Object arg, Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, new Object[]{arg}, clz, hasEntity);
	}

	@Override
	public <N extends Object>Pager<N> findBySql(String sql, Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, null, clz, hasEntity);
	}

	@Override
	public <N extends Object>Pager<N> findBySql(String sql, Object[] args, Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		String cq =this.getCountHql(sql,false);
		sql = initSort(sql);
		cq = this.getCountHql(sql, false);
		SQLQuery cQuery = getSession().createSQLQuery(cq);
		SQLQuery query = getSession().createSQLQuery(sql);
		this.setAliasParameter(cQuery, alias);
		this.setAliasParameter(query, alias);
		this.setParameter(query, args);
		this.setParameter(cQuery, args);
		Pager<N> pages = new Pager<N>();
		this.setPagers(query, pages);
		if(hasEntity){
			query.addEntity(clz);
		}else{
			query.setResultTransformer(Transformers.aliasToBean(clz));
		}
		List<N> datas = query.list();
		long total = ((BigInteger)cQuery.uniqueResult()).intValue();
		pages.setTotal(total);
		pages.setDatas(datas);
		return pages;
	}

	@Override
	public <N extends Object>Pager<N> findByAliasSql(String sql, Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, null, alias, clz, hasEntity);
	}

}
